package main

import (
	"fmt"
)

// 结构体
type vertex struct {
	X float64
	Y float64
}

func Run3() {
	fmt.Println("Run3 --------------------------------")

	// 指针 Go没有指针运算，作为一种引用来使用
	i, j := 42, 2701

	p := &i         // point to i
	fmt.Println(*p) // read i through the pointer
	*p = 21         // set i through the pointer
	fmt.Println(i)  // see the new value of i

	p = &j         // point to j
	*p = *p / 37   // divide j through the pointer
	fmt.Println(j) // see the new value of j

	// 结构体 {X:1, Y:2}
	fmt.Println(vertex{1, 2})

	// 数组 不能改变大小
	var a [2]string
	a[0] = "Hello"
	a[1] = "World"
	fmt.Println(a)

	// slice 类似动态数组
	sc := []int{2, 3, 5, 7, 11, 13}
	fmt.Println("sc ==", sc)
	for i := 0; i < len(sc); i++ {
		fmt.Printf("sc[%d] == %d\n", i, sc[i])
	}

	// slice切片 下标含前不含后 sc[i:i]为空 sc[i:i+1]有一个
	fmt.Println("sc[1:4] ==", sc[1:4]) // 3 5 7

	// 构造slice
	sc2 := make([]int, 5)  		//len=5 cap=5 [0 0 0 0 0]
	sc3 := make([]int, 4, 8)  	//len=4 cap=8 [0 0 0 0]
	fmt.Printf("len=%d cap=%d %v\n", len(sc2), cap(sc2), sc2)
	fmt.Printf("len=%d cap=%d %v\n", len(sc3), cap(sc3), sc3)

	// slice 零值nil
	var sc4 []int
	if sc4 == nil {
		fmt.Println("sc4 == nil", sc4, len(sc4), cap(sc4))
	}

	// slice 添加元素 func append(s []T, vs ...T) []T
	sc4 = append(sc4, 666)
	sc4 = append(sc4, 777, 233, sc4[0])
	fmt.Println("sc4 append", sc4, len(sc4), cap(sc4))

	// range 迭代循环(slice,map)
	for i, v := range sc4 { //可以 _,v 或者 i
		fmt.Println(i, v)
	}

	// map
	m := make(map[string]vertex)
	m["Bell Labs"] = vertex{40.68433, -74.39967}
	m["Google"] = vertex{37.42202, -122.08408}
	fmt.Println(m)
	fmt.Println(m["Bell Labs"])

	// map 删除元素 delete
	delete(m, "Google") //如果key不存在则不删除
	fmt.Println(m)

	// map 是否存在
	val, ok := m["Google"]
	fmt.Println("val =", val, "ok =", ok)
	//val = {0 0} ok = false
	//val = {37.42202 -122.08408} ok = true

	test_closures()
}




func adder() func(int) int {
	sum := 0
	return func(x int) int {
		sum += x
		return sum
	}
}
func test_closures() {
	// 函数的闭包
	pos, neg := adder(), adder()
	for i := 0; i < 10; i++ {
		fmt.Println(pos(i), neg(i+1))
	}
}
